//
//  RoomDetailView.m
//  ThuePhongDep
//
//  Created by Huynh Chi Hung on 8/1/13.
//  Copyright (c) 2013 Huynh Chi Hung. All rights reserved.
//

#import "RoomDetailView.h"
#import "UIImageView+WebCache.h"
#import "Define.h"
#import "SBJSON.h"
#import "AppViewController.h"

@implementation RoomDetailView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        CGFloat colors[8] = {
            0, 0, 0, 0.5,
            0, 0, 0, 0.5
        };
        // Initialization code
        self.margin = UIEdgeInsetsMake(15, 12, 10, 12);

        [[self titleBar] setColorComponents:colors];
        self.contentColor = [UIColor colorWithWhite:0.0 alpha:0.8];

        // The gradient style (Linear, linear reversed, radial, radial reversed, center highlight). Default = UAGradientBackgroundStyleLinear
        [[self titleBar] setGradientStyle:UAGradientBackgroundStyleLinear];
        
        // The line mode of the gradient view (top, bottom, both, none). Top is a white line, bottom is a black line.
//        [[self titleBar] setLineMode: pow(2, (arc4random() % 3))];
        
        // The noise layer opacity. Default = 0.4
//        [[self titleBar] setNoiseOpacity:0.4];
        
        // The header label, a UILabel with the same frame as the titleBar
        [self headerLabel].font = [UIFont boldSystemFontOfSize:floor(self.titleBarHeight / 2.0)];
        
        _APIRequester = [APIRequester new];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame title:(NSString*)title roomID:(NSString *)roomID {
    self = [self initWithFrame:frame];
    if (self) {
        self.headerLabel.text = title;
        _roomID = roomID;
        _pageImageView = [[UIScrollView alloc] initWithFrame:CGRectZero];
        _pageImageView.pagingEnabled = YES;
        _pageImageView.delegate = self;
        _pageImageView.hidden = YES;
//        _imageView = [[UIImageView alloc] initWithFrame:CGRectZero];
//        _imageView.contentMode = UIViewContentModeScaleAspectFit;
        [self.contentView addSubview:_pageImageView];
        _pageControl = [[UIPageControl alloc] initWithFrame:CGRectZero];
        [self.contentView addSubview:_pageControl];
        _pageControl.hidden = YES;
        _pageControl.numberOfPages = 1;
        [_pageControl setCurrentPage:0];
        
//        [_imageView release];
        
//        spinner = [[UIActivityIndicatorView alloc]
//                   initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
//        spinner.center = _imageView.center;
//        [spinner startAnimating];
//        [_imageView addSubview:spinner];
//        [spinner release];
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.rowHeight = 40;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.backgroundView = nil;
        _tableView.hidden = YES;
        [self.contentView addSubview:_tableView];

        
        [self requestWithRoomID:_roomID];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    [_pageImageView setFrame:CGRectMake(0, 0,self.contentView.bounds.size.width, self.contentView.bounds.size.width*2/3)];
    [_pageControl setFrame:CGRectMake(0, self.contentView.bounds.size.width*2/3 + 2,self.contentView.bounds.size.width, 5)];
//    spinner.center = _imageView.center;
    [_tableView setFrame:CGRectMake(0, self.contentView.bounds.size.width*2/3 + 10, self.contentView.bounds.size.width, self.contentView.bounds.size.height - self.contentView.bounds.size.width*2/3 - 13)];
}

- (void)loadInterface {
    _pageImageView.hidden = NO;
    _pageControl.hidden = NO;
    _tableView.hidden = NO;
    [_tableView reloadData];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

-(void)requestWithRoomID:(NSString *)roomID
{
    NSString *requestURL = STRING_REQUEST_URL_PHONGDEP_GET_ROOM_DETAIL(roomID);
    [_APIRequester requestWithType:ENUM_API_REQUEST_TYPE_PHONGDEP_GET_ROOM_DETAIL andRootURL:requestURL andPostMethodKind:YES andParams:nil andDelegate:self];
    
#ifdef __DEBUG__
    NSLog(@"requestTheNext: %@", requestURL);
#endif
}

- (void)requestFinished:(ASIHTTPRequest *)request andType:(ENUM_API_REQUEST_TYPE)type {
//#ifdef __DEBUG__
//    NSLog(@"requestFinished %@, request.responseStatusCode: %i", request.responseString, request.responseStatusCode);
//#endif
    
    [[AppViewController Shared] isRequesting:NO andRequestType:ENUM_API_REQUEST_TYPE_INVALID andFrame:CGRectZero];
    
    NSError *error;
    SBJSON *sbJSON = [SBJSON new];
    
    if (![sbJSON objectWithString:[request responseString] error:&error] || request.responseStatusCode != 200 || !request) {
//        if (![ASIHTTPRequest isNetworkReachable]) {
//            ALERT(STRING_ALERT_CONNECTION_ERROR_TITLE, STRING_ALERT_SERVER_ERROR);
//        }
#ifdef __DEBUG__
#else
        if (type != ENUM_API_REQUEST_TYPE_USER_UPDATE_DEVICE_TOKEN && type != ENUM_API_REQUEST_TYPE_USER_UPDATE_DEVICE_UDID && type != ENUM_API_REQUEST_TYPE_USER_UPDATE_USER_INFO) {
            ALERT(STRING_ALERT_CONNECTION_ERROR_TITLE, STRING_ALERT_SERVER_ERROR);
        }
#endif
        return;
    }
    
    NSMutableDictionary *jsonData = [[sbJSON objectWithString:[request responseString] error:&error] objectForKey:STRING_RESPONSE_KEY_DATA];
    
    if (!jsonData || jsonData.count == 0) {
        return;
    }
    
    _jsonDataRecieved = jsonData;
    
    if (type == ENUM_API_REQUEST_TYPE_PHONGDEP_GET_ROOM_DETAIL) {
        NSArray *imageArray = [jsonData objectForKey:STRING_RESPONSE_KEY_IMAGES];
        int totalImage =  [imageArray count];
        _pageControl.numberOfPages = totalImage;
        [_pageControl setCurrentPage:0];
        _pageImageView.contentSize = CGSizeMake(_pageImageView.frame.size.width*totalImage, _pageImageView.frame.size.height);
        
        int i = 0;
        for (NSDictionary *image in imageArray) {
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(_pageImageView.frame.size.width*i + 5, 0,
                                                                                   _pageImageView.frame.size.width -10, _pageImageView.frame.size.height- 8)];
            imageView.contentMode = UIViewContentModeScaleAspectFit;
            [_pageImageView addSubview:imageView];
            NSString *imageURL = [image objectForKey:[[image allKeys] objectAtIndex:0]];
            [imageView setImageWithURL:[NSURL URLWithString:imageURL] placeholderImage:IMG_AVARTAR_DUMMY];
            
            i++;
        }
        
        // LOAD INTERFACE
        [self loadInterface];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request andType:(ENUM_API_REQUEST_TYPE)type {
//#ifdef __DEBUG__
//    NSLog(@"requestFailed %@, request.responseStatusCode: %i", request.responseString, request.responseStatusCode);
//#endif
    
    [[AppViewController Shared] isRequesting:NO andRequestType:ENUM_API_REQUEST_TYPE_INVALID andFrame:CGRectZero];
    
    if (![ASIHTTPRequest isNetworkReachable] && type != ENUM_API_REQUEST_TYPE_USER_UPDATE_DEVICE_TOKEN && type != ENUM_API_REQUEST_TYPE_USER_UPDATE_DEVICE_UDID && type != ENUM_API_REQUEST_TYPE_USER_UPDATE_USER_INFO) {
        ALERT(STRING_ALERT_CONNECTION_ERROR_TITLE, STRING_ALERT_CONNECTION_ERROR);
    }
}

#pragma mark - TableView

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 40)];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, headerView.frame.size.width-20, 40)];
    static NSString* boldFontName = FONT_APP_BOLD;
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont fontWithName:boldFontName size:16];
    label.backgroundColor = [UIColor clearColor];
    if (section  == 0) {
        label.text = @"Thông tin Phòng";
    }
    else if (section == 1) {
        label.text = @"Tiện nghi bao gồm";
    }
    else if (section == 2) {
        label.text = @"Tiện nghi tùy chọn";
    }
    [headerView addSubview:label];
    return  headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 2) {
        return 100;
    }
    return 0;
}


- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section == 2) {
        UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 100)];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, footer.frame.size.width-20, 100)];
        static NSString* boldFontName = FONT_APP_BOLD;
        label.textColor = [UIColor whiteColor];
        label.font = [UIFont fontWithName:boldFontName size:14];
        label.numberOfLines = 10;
        label.backgroundColor = [UIColor clearColor];
        label.text = @"Ngoài những tiện nghi đã có sẵn, với hợp đồng từ 6 tháng trở lên, bạn có thể tuỳ chọn thêm những tiện nghi mới. Việc tuỳ chọn tiện nghi có thể làm thay đổi giá thuê phòng của bạn.";
        [footer addSubview:label];
        return  footer;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.section == 0 && indexPath.row == 2) {
        return 60;
    }
    return 40;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section  == 0) {
        // Name,Address,Price + Service
        NSDictionary *services = [_jsonDataRecieved objectForKey:@"services"];
        if (!services)
            return 4;
        return 4 + [services count];
    }
    else if (section == 1) {
        NSDictionary *features = [_jsonDataRecieved objectForKey:@"features"];
        if (!features)
            return 0;
        id object = [features objectForKey:@"included_features"];
        if ([object isKindOfClass:[NSArray class]]) {
            NSArray *includedFeatures = (NSArray*) object;
            if (includedFeatures)
                return [includedFeatures count];
        }
        else
            return 0;
    }
    else if (section == 2) {
        NSDictionary *features = [_jsonDataRecieved objectForKey:@"features"];
        if (!features)
            return 0;
        id object = [features objectForKey:@"new_features"];
        if ([object isKindOfClass:[NSArray class]]) {
            NSArray *newFeatures = (NSArray*) object;
            return [newFeatures count];
        }
        else
            return 0;
    }
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
	NSString *cellIdentifier = @"UAModalPanelCell";
//    static NSString* fontName = @"Avenir";
    static NSString* boldFontName = FONT_APP_BOLD;

	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
	if (cell == nil) {
		cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.backgroundColor = [UIColor colorWithWhite:244/255.f alpha:1.0];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.textColor = [UIColor colorWithRed:52/255.f green:56/255.f blue:60/255.f alpha:1.0];
        cell.textLabel.font = [UIFont fontWithName:boldFontName size:14];
        cell.textLabel.numberOfLines = 3;
	}
    int section = indexPath.section;
    NSDictionary *services = [_jsonDataRecieved objectForKey:@"services"];
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    numberFormatter.groupingSeparator = @".";
    numberFormatter.decimalSeparator = @",";
    [numberFormatter setNumberStyle: NSNumberFormatterDecimalStyle];

	if (section  == 0) {

        if (indexPath.row == 0) {
            CGFloat price = [[_jsonDataRecieved objectForKey:@"price"] floatValue];
            cell.textLabel.text = [NSString stringWithFormat:@"Giá thuê: %@ đ",
                              [numberFormatter stringFromNumber:[NSNumber numberWithFloat:price]]];
        }
        else if (indexPath.row == 1) {
            cell.textLabel.text = [NSString stringWithFormat:@"Diện tích: %@ m2",
                                   [_jsonDataRecieved objectForKey:@"area"]];
        }
        else if (indexPath.row == 2) {
            NSString *address = [_jsonDataRecieved objectForKey:@"address"];
            NSString *district = [_jsonDataRecieved objectForKey:@"district"];
            NSString *city = [_jsonDataRecieved objectForKey:@"city"];
            cell.textLabel.text = [NSString stringWithFormat:@"Địa chỉ: %@, Quận %@, Tỉnh/TP %@.",address,district,city];            
        }
        else if (indexPath.row == 3) {
            int status = [[_jsonDataRecieved objectForKey:@"status"] intValue];
            if (status == 0) {
                cell.textLabel.text = @"Tình trạng: Phòng đang trống";
            }
            else {
                cell.textLabel.text = [NSString stringWithFormat:@"Tình trạng: Đang cho thuê (%d ngày nữa trống)",status];
            }
        }
        
        else if (indexPath.row == 4) {
            CGFloat price = [[services objectForKey:@"electricity"] floatValue];
            cell.textLabel.text = [NSString stringWithFormat:@"Tiền điện: %@ đ/KWh",
                                   [numberFormatter stringFromNumber:[NSNumber numberWithFloat:price]]];        
        }
        else if (indexPath.row == 5) {
            CGFloat price = [[services objectForKey:@"water"] floatValue];
            cell.textLabel.text = [NSString stringWithFormat:@"Tiền nước: %@ đ/người",
                                   [numberFormatter stringFromNumber:[NSNumber numberWithFloat:price]]];
        }
        else if (indexPath.row == 6) {
            CGFloat price = [[services objectForKey:@"internet"] floatValue];
            cell.textLabel.text = [NSString stringWithFormat:@"Internet: %@ đ",
                                   [numberFormatter stringFromNumber:[NSNumber numberWithFloat:price]]];
        }
        else if (indexPath.row == 7) {
            CGFloat price = [[services objectForKey:@"cable_tv"] floatValue];
            cell.textLabel.text = [NSString stringWithFormat:@"Truyền hình cáp: %@ đ",
                                   [numberFormatter stringFromNumber:[NSNumber numberWithFloat:price]]];
        }
        else if (indexPath.row == 8) {
            CGFloat price = [[services objectForKey:@"washing_machine"] floatValue];
            cell.textLabel.text = [NSString stringWithFormat:@"Máy giặt: %@ đ",
                                [numberFormatter stringFromNumber:[NSNumber numberWithFloat:price]]];
        }

    }
    else if (section == 1) {
        NSDictionary *features = [_jsonDataRecieved objectForKey:@"features"];
        NSArray *includedFeatures = [features objectForKey:@"included_features"];
        NSDictionary *includedFeature = [includedFeatures objectAtIndex:[indexPath row]];
        NSDictionary *feature = [includedFeature objectForKey:[[includedFeature allKeys] objectAtIndex:0]];
        CGFloat price = [[feature objectForKey:@"price"] floatValue];
        
        cell.textLabel.text = [NSString stringWithFormat:@"%@: %@ đ",[feature objectForKey:@"name"],
                               [numberFormatter stringFromNumber:[NSNumber numberWithFloat:price]]];

    }
    else if (section == 2) {
        NSDictionary *features = [_jsonDataRecieved objectForKey:@"features"];
        NSArray *newFeatures = [features objectForKey:@"new_features"];
        NSDictionary *newFeature = [newFeatures objectAtIndex:[indexPath row]];
        NSDictionary *feature = [newFeature objectForKey:[[newFeature allKeys] objectAtIndex:0]];
        CGFloat price = [[feature objectForKey:@"price"] floatValue];
        cell.textLabel.text = [NSString stringWithFormat:@"%@: %@ đ",[feature objectForKey:@"name"],
                               [numberFormatter stringFromNumber:[NSNumber numberWithFloat:price]]];
    }
    
	return cell;
}

#pragma scroolViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)sender {
    // Update the page when more than 50% of the previous/next page is visible
    if (sender == _pageImageView) {
        CGFloat pageWidth = _pageImageView.frame.size.width;
        int page = floor((_pageImageView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
        _pageControl.currentPage = page;
    }
}

@end
